import asyncHandler from "express-async-handler"
import Cart from "../models/Cart.js"

/**
 * 获取购物车列表
 */
export const getCartItems = asyncHandler(async (req, res) => {
  const data = await Cart.find({ user: req.user.id }).populate({ path: 'user' }).populate({ path: 'product' })
  res.json({
    success: true,
    msg: '',
    data
  })
})

/**
 * 添加至购物车
 * @param {String} productId 商品id
 */
export const addProductToCart = asyncHandler(async (req, res) => {
  const { productId, qty } = req.body

  /* 判断数据库中 同一个用户是否有相同商品订单 */
  let cart = await Cart.findOne({
    user: req.user.id,
    product: productId,
  })

  if (cart) {
    cart.qty += qty
  } else {
    cart = new Cart({
      user: req.user.id,
      product: productId,
      qty
    })
  }
  await cart.save()
  res.json({
    success: true,
    msg: '',
    data: cart
  })
})

/**
 * 从购物车删除
 * @param {String} cartId 购物车对应列的id
 */
export const delProductToCart = asyncHandler(async (req, res) => {
  const cart = await Cart.findById(req.params.cartId)
  await cart.remove()
  res.json({
    success: true,
    msg: '',
    data: null
  })
})

/**
 * 修改购物车商品数量
 * @param {String} cartId 购物车对应列的id
 * @param {Number} qty 数量
 */
export const updateProductToCart = asyncHandler(async (req, res) => {
  const cart = await Cart.findById(req.params.cartId)
  cart.qty = req.body.qty
  await cart.save()
  res.json({
    success: true,
    msg: '',
    data: cart
  })
})